package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"runtime/debug"
	"strings"
	"time"
)

var logger *zap.Logger
var sugarLogger *zap.SugaredLogger

//func main() {
//	InitLogger2()
//	defer sugarLogger.Sync()
//	simpleHtpGet("www.sogou.com")
//	simpleHtpGet("https://www.sogou.com")
//}

func main() {
	InitLogger2()
	//r := gin.Default()
	r := gin.New()
	//在gin框架中使用我们上面定义好的两个中间件来代替gin框架默认的Logger()和Recovery()。
	r.Use(GinLogger(logger), GinRecovery(logger, true))

	r.GET("/hello", func(context *gin.Context) {
		context.String(http.StatusOK, "Hello xyy!")
	})
	r.Run()
}

//func InitLogger() {
//	logger, _ = zap.NewProduction()
//}

func simpleHtpGet(url string) {
	resp, err := http.Get(url)
	if err != nil {
		sugarLogger.Error(
			"Error fetching url...",
			zap.String("url", url),
			zap.Error(err))
	} else {
		sugarLogger.Info("Success...",
			zap.String("statusCode", resp.Status),
			zap.String("url", url))
		resp.Body.Close()
	}
}

func InitLogger2() {
	writeSyncer := getLogWriter()
	encoder := getEncoder2()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	sugarLogger = logger.Sugar()
}

func getEncoder() zapcore.Encoder {
	return zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig())
}

func getEncoder2() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	//file, _ := os.Create("./05_zap_demo/test.log")
	//file, _ := os.OpenFile("./05_zap_demo/test.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0744)
	limberJackLogger := &lumberjack.Logger{
		Filename:   "./05_zap_demo/test.log",
		MaxSize:    1,
		MaxAge:     5,
		MaxBackups: 30,
		LocalTime:  false,
		Compress:   false,
	}
	return zapcore.AddSync(limberJackLogger)
}

// GinLogger 接收 gin 框架默认的日志
func GinLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(context *gin.Context) {
		start := time.Now()
		path := context.Request.URL.Path
		query := context.Request.URL.RawQuery
		context.Next()

		cost := time.Since(start)
		logger.Info(path,
			zap.Int("status", context.Writer.Status()),
			zap.String("method", context.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", context.ClientIP()),
			zap.String("user-agent", context.Request.UserAgent()),
			zap.String("errors", context.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}

// GinRecovery recover掉项目可能出现的 panic
func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc {
	return func(context *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				//检查连接是否断开，因为这并不是真正需要进行恐慌堆栈跟踪的情况
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(context.Request, false)
				if brokenPipe {
					logger.Error(context.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					//如果连接已断开，我们就无法写入状态
					context.Error(err.(error)) //nolint: errcheck
					context.Abort()
					return
				}
				if stack {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}
				context.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
		context.Next()
	}
}
